<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="部门ID" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入部门ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="当前任务ID" prop="currentTaskId">
        <el-input
          v-model="queryParams.currentTaskId"
          placeholder="请输入当前任务ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="产线编号" prop="lineNo">
        <el-input v-model="queryParams.lineNo" placeholder="请输入产线编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工序号" prop="processNo">
        <el-input v-model="queryParams.processNo" placeholder="请输入工序号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工序名称" prop="processName">
        <el-input v-model="queryParams.processName" placeholder="请输入工序名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="当前车辆顺序" prop="vehicleSequence">
        <el-input
          v-model="queryParams.vehicleSequence"
          placeholder="请输入当前车辆顺序"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="工序类型" prop="processType">
        <el-select v-model="queryParams.processType" placeholder="请选择工序类型" clearable>
          <el-option v-for="dict in processTypes" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="作业类型" prop="jobType">
        <el-select v-model="queryParams.jobType" placeholder="请选择作业类型" clearable>
          <el-option v-for="dict in jobTypes" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="初始人数" prop="initialPeople">
        <el-input v-model="queryParams.initialPeople" placeholder="请输入初始人数" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="当前人数" prop="currentPeople">
        <el-input v-model="queryParams.currentPeople" placeholder="请输入当前人数" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="最大人数" prop="maxPeople">
        <el-input v-model="queryParams.maxPeople" placeholder="请输入当前人数" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['zndd:process:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['zndd:process:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['zndd:process:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['zndd:process:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['zndd:process:import']">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="processList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <!-- <el-table-column label="部门ID" align="center" prop="deptId" /> -->
      <el-table-column label="当前任务" width="150" align="center" prop="currentTaskId" :formatter="taskFomatter" />
      <el-table-column label="产线编号" width="150" align="center" prop="lineNo" />
      <el-table-column label="工序号" width="150" align="center" prop="processNo" />
      <el-table-column label="工序名称" width="150" align="center" prop="processName" />
      <el-table-column label="工序类型" width="150" align="center" prop="processType" :formatter="processTypeFomatter" />
      <el-table-column label="作业类型" width="150" align="center" prop="jobType" :formatter="jobTypeFomatter" />
      <el-table-column label="当前车辆顺序" width="150" align="center" prop="vehicleSequence" />
      <el-table-column label="生产线顺序" width="150" align="center" prop="productionLineSequence" />
      <el-table-column label="初始人数" width="150" align="center" prop="initialPeople" />
      <el-table-column label="当前人数" width="150" align="center" prop="currentPeople" />
      <el-table-column label="最大人数" width="150" align="center" prop="maxPeople" />
      <!-- <el-table-column label="替代工序" width="150" align="center" prop="alternativeProcess"
        :formatter="alternativeFomatter" /> -->
      <el-table-column label="备注" width="150" align="center" prop="remark" />
      <el-table-column label="操作" width="200" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['zndd:process:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['zndd:process:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工序信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="部门ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门ID" />
        </el-form-item>
        <el-form-item label="当前任务ID" prop="currentTaskId">
          <el-input v-model="form.currentTaskId" placeholder="请输入当前任务ID" />
        </el-form-item> -->
        <el-form-item label="产线编号" prop="lineNo">
          <el-input v-model="form.lineNo" placeholder="请输入产线编号" />
        </el-form-item>
        <el-form-item label="工序号" prop="processNo">
          <el-input v-model="form.processNo" placeholder="请输入工序号" />
        </el-form-item>
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="form.processName" placeholder="请输入工序名称" />
        </el-form-item>
        <el-form-item label="工序类型" prop="processType">
          <el-select v-model="form.processType" placeholder="请选择工序类型">
            <el-option v-for="dict in processTypes" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="作业类型" prop="jobType">
          <el-select v-model="form.jobType" placeholder="请选择作业类型">
            <el-option v-for="dict in jobTypes" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产线顺序" prop="productionLineSequence">
          <el-input v-model="form.productionLineSequence" placeholder="请输入生产线顺序" />
        </el-form-item>
        <!-- <el-form-item label="初始人数" prop="initialPeople" v-if="form.processType == 2">
          <el-input v-model="form.initialPeople" placeholder="请输入初始人数" />
        </el-form-item>
        <el-form-item label="最大人数" prop="maxPeople" v-if="form.processType == 2">
          <el-input v-model="form.maxPeople" placeholder="请输入最大人数" />
        </el-form-item> -->
        <!-- <el-form-item label="当前人数" prop="currentPeople">
          <el-input v-model="form.currentPeople" placeholder="请输入当前人数" />
        </el-form-item> -->
        <!-- <el-form-item label="替代工序" prop="alternativeProcess" v-if="this.title == '修改工序信息'">
          <el-select v-model="processCurrentAlternative" multiple collapse-tags placeholder="请选择需要替代的工序">
            <el-option v-for="item in processAlternativeList" :key="item.id" :label="item.label" :value="item.id">
            </el-option>
          </el-select> -->
          <!-- <el-input v-model="form.alternativeProcess" placeholder="请输入替代工序" /> -->
        <!-- </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 工序导入对话框 -->
    <el-dialog style="align-content: center;" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的工序数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProcess, getProcess, delProcess, addProcess, updateProcess, listQualification, listAlternative, listAllprocess } from "@/api/zndd/process/process";
import { getToken } from "@/utils/auth";
import { getDicts } from "@/api/system/dict/data";
import { listAllSet } from "@/api/zndd/line/set";
import { listTask } from "@/api/zndd/task/task";

export default {
  name: "Process",
  data() {
    return {
      //全部工序信息
      listProcess: [],
      //工序类型列表
      processTypes: [],
      //作业类型列表
      jobTypes: [],
      //工序可以替代的工序列表
      processAlternativeList: [],
      //选中工序可以替代工序的数组
      processCurrentAlternative: [],
      //三级产线列表
      // threeLineList:[],
      //任务信息列表
      taskList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工序信息表格数据
      processList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        lineId: null,
        lineNo: null,
        currentTaskId: null,
        processNo: null,
        processName: null,
        processType: null,
        jobType: null,
        vehicleSequence: null,
        productionLineSequence: null,
        initialPeople: null,
        currentPeople: null,
        maxPeople: null,
        alternativeProcess: null,
      },
      // 表单参数
      form: {},
      // 工序导入参数
      upload: {
        // 是否显示弹出层（工序导入）
        open: false,
        // 弹出层标题（工序导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的工序数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/zndd/process/importData"
      },
      // 表单校验
      rules: {
        lineNo: [
          { required: true, message: "产线编号不能为空", trigger: "blur" }
        ],
        processNo: [
          { required: true, message: "工序号不能为空", trigger: "blur" }
        ],
        processName: [
          { required: true, message: "工序名称不能为空", trigger: "blur" }
        ],
        processType: [
          { required: true, message: "工序类型不能为空", trigger: "blur" }
        ],
        jobType: [
          { required: true, message: "作业类型不能为空", trigger: "blur" }
        ],
        productionLineSequence: [
          { required: true, message: "产线顺序不能为空", trigger: "blur" }
        ],
        initialPeople: [
          { required: true, message: "初始人数不能为空", trigger: "blur" }
        ],
        maxPeople: [
          { required: true, message: "最大人数不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    listTask().then(response => {
      this.taskList = response.rows;
    })
    listAllprocess().then(response => {
      this.listProcess = response.rows;
    })
    //获取字典表中工序类型
    this.getDicts("zndd_process_type").then(response => {
      this.processTypes = response.data;
    });
    //获取字典表中作业类型
    this.getDicts("zndd_job_type").then(response => {
      this.jobTypes = response.data;
    });
    // //获取三级产线列表
    // listAllSet().then(response => {
    //   this.threeLineList = response.rows;
    // })
    this.getList();
  },
  methods: {
    //格式化产线名称
    // lineFomatter(row, column){
    //   var tl = null;
    //   this.threeLineList.forEach(threeLine => {
    //     if (threeLine.id == row.lineId) {
    //       tl = threeLine;
    //     }
    //   });
    //   if(tl == null){
    //     return "";
    //   }else{
    //     return tl.threeLineName;
    //   }
    // },
    //格式化任务名称
    taskFomatter(row, column) {
      var tk = null;
      this.taskList.forEach(task => {
        if (task.id == row.currentTaskId) {
          tk = task;
        }
      });
      if (tk == null) {
        return "";
      } else {
        return tk.taskName;
      }
    },
    //格式化替代工序
    alternativeFomatter(row, column) {
      var altervativeP = "";
      if (row.alternativeProcess != null) {
        this.listProcess.forEach(rows => {
          if (row.alternativeProcess.includes(",")) {
            var arr = row.alternativeProcess.split(",");
            for (let i = 0; i < arr.length; i++) {
              if (rows.id == arr[i]) {
                if (i == arr.length - 1) {
                  altervativeP = altervativeP + rows.processName;
                } else {
                  altervativeP = altervativeP + rows.processName + ",";
                }
              }
            }
          } else {
            if (rows.id == row.alternativeProcess) {
              altervativeP = altervativeP + rows.processName;
            }
          }
        });
      }
      return altervativeP;
    },
    //格式化作业类型
    jobTypeFomatter(row, column) {
      var jt = null;
      this.jobTypes.forEach(jobType => {
        if (jobType.dictValue == row.jobType) {
          jt = jobType;
        }
      });
      if (jt == null) {
        return "";
      } else {
        return jt.dictLabel;
      }
    },
    //格式化工序类型
    processTypeFomatter(row, column) {
      var pt = null;
      this.processTypes.forEach(processType => {
        if (processType.dictValue == row.processType) {
          pt = processType;
        }
      });
      if (pt == null) {
        return "";
      } else {
        return pt.dictLabel;
      }
    },
    /** 查询工序信息列表 */
    getList() {
      this.loading = true;
      listProcess(this.queryParams).then(response => {
        this.processList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        lineId: null,
        lineNo: null,
        currentTaskId: null,
        processNo: null,
        processName: null,
        processType: null,
        jobType: null,
        vehicleSequence: null,
        productionLineSequence: null,
        initialPeople: null,
        currentPeople: null,
        maxPeople: null,
        alternativeProcess: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.processCurrentAlternative = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工序信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProcess(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工序信息";
        listAlternative(this.form).then(response => {
          var list = [];
          response.rows.forEach(row => {
            list.push({
              label: row.processName,
              id: row.id
            });
          });
          this.processAlternativeList = list;
          if(this.form.alternativeProcess != null){
            var ids = [];
            this.form.alternativeProcess.split(",").forEach(id => {
              ids.push(parseInt(id));
            });
            this.processCurrentAlternative = ids;
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.processCurrentAlternative)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.processCurrentAlternative.length > 0) {
              var ap = "";
              for (let i = 0; i < this.processCurrentAlternative.length; i++) {
                if (i == this.processCurrentAlternative.length - 1) {
                  ap = ap + this.processCurrentAlternative[i];
                } else {
                  ap = ap + this.processCurrentAlternative[i] + ",";
                }
              }
              this.form.alternativeProcess = ap;
            }
            listQualification(this.form).then(response => {
              updateProcess(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            });
          } else {
            listQualification(this.form).then(response => {
              addProcess(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的工序信息数据项？').then(function () {
        return delProcess(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('zndd/process/export', {
        ...this.queryParams
      }, `工序信息_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "工序导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('zndd/process/importTemplate', {
      }, `工序导入信息_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
